package thread_local

import (
	"fmt"
	"github.com/go-eden/routine"
	"time"
)

var nameVar = routine.NewLocalStorage()

func local() {
	nameVar.Set("hello world")
	fmt.Println("name: ", nameVar.Get())

	// 其他协程不能读取前面Set的"hello world"
	go func() {
		fmt.Println("name1: ", nameVar.Get())
	}()

	// 但是可以通过Go函数启动新协程，并将当前main协程的全部协程上下文变量赋值过去
	routine.Go(func() {
		fmt.Println("name2: ", nameVar.Get())
	})

	// 或者，你也可以手动copy当前协程上下文至新协程，Go()函数的内部实现也是如此
	ic := routine.BackupContext()
	go func() {
		routine.InheritContext(ic)
		fmt.Println("name3: ", nameVar.Get())
	}()

	time.Sleep(time.Second)
}

func thread() {
	go func() {
		goId := routine.Goid()
		fmt.Printf("inner goId: %d\n", goId)
		time.Sleep(time.Second)
	}()
	goId := routine.Goid()
	goIds := routine.AllGoids()
	fmt.Printf("curr goId: %d\n", goId)
	fmt.Printf("all goIds: %v\n", goIds)
}
